package com.easondongh.business.controller;

import com.easondongh.business.domain.GoodsBack;
import com.easondongh.business.domain.GoodsImport;
import com.easondongh.business.service.GoodsBackService;
import com.easondongh.business.service.GoodsImportService;
import com.easondongh.business.vo.GoodsBackQueryVo;
import com.easondongh.common.enums.ResponseEnum;
import com.easondongh.common.response.ResponseObj;
import com.easondongh.common.vo.BasePageQueryVo;
import com.easondongh.common.vo.PageResult;
import com.easondongh.system.domain.SysUser;
import com.easondongh.common.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author EasonDongH
 * @date 2020/6/2 10:43
 */
@Slf4j
@RestController
@RequestMapping("/goodsBack")
public class GoodsBackController {

    @Autowired
    private GoodsBackService goodsBackService;
    @Autowired
    private GoodsImportService goodsImportService;

    @PostMapping("/processGoodsBack")
    public ResponseObj processGoodsBack(@RequestBody GoodsBack goodsBack) {
        if(goodsBack == null || goodsBack.getImportId() == null || goodsBack.getGoodsId() == null) {
            log.warn("商品退货时：进货id、商品id不能为空");
            return new ResponseObj(ResponseEnum.GOODS_BACK_FAIL);
        }
        GoodsImport importData = this.goodsImportService.getById(goodsBack.getImportId());
        if(importData.getNumber() < goodsBack.getNumber()) {
            return new ResponseObj(ResponseEnum.GOODS_BACK_NUMER_INVALID);
        }
        SysUser loginUser = ShiroUtils.getCurrentLoginUser();
        goodsBack.setPayType(importData.getPayType());
        goodsBack.setBackPrice(importData.getImportPrice());
        goodsBack.setBackTime(new Date());
        goodsBack.setOperatePerson(loginUser.getName());
        this.goodsBackService.processGoodsBack(goodsBack);
        return new ResponseObj(ResponseEnum.GOODS_BACK_SUCCESS);
    }

    @PostMapping("/getByPage")
    public ResponseObj<PageResult<GoodsBack>> getByPage(@RequestBody BasePageQueryVo<GoodsBackQueryVo> queryCondition) {
        if(queryCondition == null) {
            return ResponseObj.QueryFail;
        }
        PageResult<GoodsBack> result = this.goodsBackService.getByPage(queryCondition);
        return new ResponseObj<>(ResponseEnum.QUERY_SUCCESS, result);
    }
}
